package com.ourteam.system.api;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.ourteam.frame.web.AbstractTreeNodeBuilder;
import com.ourteam.frame.web.ApplicationModel;
import com.ourteam.frame.web.MenuItem;

public class SystemAccountSubMenuNodeBuilder extends AbstractTreeNodeBuilder<MenuItem, MenuItem> {

	@Override
	public MenuItem[] getTreeNodeObjects(MenuItem parentObject) throws Exception {
		if (parentObject == null) {
			return new MenuItem[0];
		} else {
			return parentObject.getSubItems();
		}

	}

	@Override
	public Object getNodeId(MenuItem childObject) {
		return childObject.getMenuId();
	}

	public boolean isLeaf(MenuItem childObject) throws Exception {

		return childObject.hasSubItems() == false;
	}
	
	@Override
	public int getChildCount(MenuItem childObject) throws Exception {
		return ArrayUtils.isNotEmpty(childObject.getSubItems()) ? childObject.getSubItems().length : 0;
	}

	@Override
	public String getNodeDefineId(MenuItem childObject) throws Exception {
		return "menuItem";
	}

	@Override
	public MenuItem converToParentObject(Object parent) throws Exception {

		Subject subject = SecurityUtils.getSubject();

		ApplicationModel appModel = (ApplicationModel) subject.getPrincipal();

		List<MenuItem> findMenuItems = new ArrayList<MenuItem>();

		findMenuItem(parent, appModel.getMenuItems(), findMenuItems);

		return findMenuItems.size() > 0 ? findMenuItems.get(0) : null;
	}

	protected void findMenuItem(Object parent, MenuItem[] menuItems, List<MenuItem> findMenuItems) {
		for (int i = 0; i < menuItems.length; i++) {
			MenuItem menuItem = menuItems[i];
			if (menuItem.getMenuId() == Long.parseLong(parent.toString())) {
				findMenuItems.add(menuItem);
			}

			if (menuItem.hasSubItems()) {
				findMenuItem(parent, menuItem.getSubItems(), findMenuItems);
			}
		}

	}

}
